<?php

namespace app\api\service;

use app\common\Helper;
use app\admin\model\Advertise;
use app\admin\model\Store;
use app\admin\model\Advertisestoreconnect;
use app\admin\model\Storetradedetail;

use think\Db;
use think\Exception;
use think\Loader;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

class AdWxNotify extends \WxPayNotify{

    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>

    public function NotifyProcess($data, &$msg){
        if($data['result_code'] == 'SUCCESS'){
            $orderNo = $data['out_trade_no'];
            $paytime = WxNotify::timeFormat($data['time_end']);
            Db::startTrans();
            try{
                $order = Advertise::where('id',$orderNo)->lock(true)->find();
                if($order->payStatus == 0){
                    Advertise::where('id',$order->id)->update(['payStatus'=>1,'status'=>1]);
                    $Advertisestoreconnect = Advertisestoreconnect::where('advertiseId',$orderNo)->find();
                    $store = Store::get($Advertisestoreconnect->storeId);
                    $Storetradedetail = new Storetradedetail();
                    $Storetradedetail->id = Helper::getUUID();
                    $Storetradedetail->orderNO = $orderNo;
                    $Storetradedetail->payMoney = $order->advertiseCost;
                    $Storetradedetail->currentStatus = '已支付';
                    $Storetradedetail->merchandise = '广告';
                    $Storetradedetail->payDeclare = '广告投放支付';
                    $Storetradedetail->payStoreId = $Advertisestoreconnect->storeId;
                    $Storetradedetail->payStoreName = $store->name;
                    $Storetradedetail->payTime = $paytime;
                    $Storetradedetail->payType = 0;
                    $Storetradedetail->save();

                    Db::commit();
                    return true;
                }
            }catch (Exception $ex){
                Db::rollback();
                return false;
            }
        }else{
            return true;
        }
    }
}